<template>
    <div>
        <a-form layout="inline"
                :model="searchData"
                style="margin: 10px 0">
            <a-form-item>
                <a-input v-model:value="searchData.keyWord" placeholder="请输入关键字"></a-input>
            </a-form-item>
            <a-form-item>
                <a-space>
                    <a-button type="primary" @click="load">搜索</a-button>
                    <a-button type="default" @click="rest">重置</a-button>
                </a-space>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-bottom: 10px" @click="openModal({})">新增</a-button>
        <a-table :dataSource="itemList"
                 :columns="columns"
                 :pagination="pagination"
                 :scroll="{ x: 2000, y: 400 }"
                 @change="handlerChange"
                 bordered>
            <template #action="{text,record}">
                <a-button type="primary" @click="openModal(record)">编辑</a-button>
                <a-popconfirm
                        title="删除数据无法恢复，请确认是否删除？"
                        ok-text="是"
                        cancel-text="否"
                        @confirm="okDelete(record.id)"
                >
                    <a-button type="danger">删除</a-button>
                </a-popconfirm>
            </template>
        </a-table>
        <a-modal v-model:visible="visible" title="新增或编辑" @ok="handleOk">
            <a-form v-model="item"
                    :label-col="{ span: 8 }">
                <a-form-item label="商品标题">
                    <a-input v-model:value="item.title"></a-input>
                </a-form-item>
                <a-form-item label="图片">
                    <a-upload
                            v-model:file-list="fileList"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            action="http://localhost:9999/mall-contents/upload"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                    >
                        <img v-if="item.image" :src="item.image" style="width: 100px;height: 100px;" alt="avatar" />
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <a-form-item label="商品卖点">
                    <a-textarea v-model:value="item.sellPoint" :auto-size="{minRows: 2, maxRows: 5}"></a-textarea>
                </a-form-item>
                <a-form-item label="价格">
                    <a-input-number v-model:value="item.price">
                        <template #addonAfter>元</template>
                    </a-input-number>
                </a-form-item>
                <a-form-item label="库存">
                    <a-input-number v-model:value="item.num"></a-input-number>
                </a-form-item>
                <a-form-item label="所属类型">
                    <a-cascader
                            v-model:value="item.categoryIds"
                            :field-names="{ label: 'name', value: 'id',children: 'children'}"
                            :options="categoryList"
                            @change="cascaderChange"
                            placeholder="Please select"
                    />
                </a-form-item>
                <a-form-item label="状态">
                    <a-select v-model:value="item.status">
                        <a-select-option :value="'1'">正常</a-select-option>
                        <a-select-option :value="'2'">下架</a-select-option>
                        <a-select-option :value="'3'">删除</a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts">
    import {ref, onMounted} from 'vue'
    import {message} from 'ant-design-vue'
    import axios from 'axios'
    import {LoadingOutlined,PlusOutlined} from '@ant-design/icons-vue'
    import {arrayToTree} from "@/util/Tool";
    export default {
        name: "admin-goods",
        components:{
            LoadingOutlined,
            PlusOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                    width: '8%',
                    fixed: 'left'
                },
                {
                    title: '标题',
                    dataIndex: 'title',
                    key: 'title',
                },
                {
                    title: '卖点',
                    dataIndex: 'sellPoint',
                    key: 'sellPoint',
                },
                {
                    title: '价格',
                    dataIndex: 'price',
                    key: 'price',
                },
                {
                    title: '库存',
                    dataIndex: 'num',
                    key: 'num',
                },
                {
                    title: '图片',
                    dataIndex: 'image',
                    key: 'image',
                },
                {
                    title: '所属类目',
                    dataIndex: 'categoryid',
                    key: 'categoryid',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    width: '200px',
                    fixed: 'right'
                },
            ]

            const searchData = ref({
                keyWord: null
            })
            const item = ref({image:null,categoryid:0,categoryIds:[]})
            const itemList = ref()
            const categoryList = ref()
            const tempValue = ref()
            const visible = ref(false)
            const pagination = ref({
                current: 1,
                pageSize: 10,
                total: 0
            })

            const fileList = ref()
            const loading = ref(false)
            const handleChange = (info:any) => {
                if (info.file.status === 'uploading') {
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("上传完成",info)
                    item.value.image = info.file.response
                    loading.value = false
                }
                if (info.file.status === 'error') {
                    loading.value = false;
                    message.error('upload error');
                }
            };
            const beforeUpload = (file:any) => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt2M;
            };

            const load = () => {
                axios.get('/mall-manager/items/list', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        keyWord: searchData.value.keyWord,
                    }
                }).then(rs => {
                    console.log("查找的结果：", rs)
                    itemList.value = rs.data.data.list
                    pagination.value.total = rs.data.data.total
                })
            }

            const handlerChange = (pageInfo:any) => {
                pagination.value = pageInfo
                load()
            }

            const rest = () => {
                searchData.value = {keyWord: null}
                load()
            }

            const openModal = (obj:any) => {
                item.value = JSON.parse(JSON.stringify(obj))
                console.log("模态框数据",item)
                if (item.value.categoryid != null) {
                    axios.get('/mall-manager/category/queryParentsById/' + obj.categoryid).then(rs=>{
                        item.value.categoryIds = rs.data.data
                        console.log("要修改的数据",item.value)
                    })
                }
                visible.value = true
            }

            const cascaderChange = (value:number[], selectedOptions:any) => {
                console.log('value',value)
                console.log('options',selectedOptions)

                // tempValue.value = value[value.length - 1]
            }

            const handleOk = () => {
                console.log("提交的数据", item)

                // item.value.categoryid = tempValue.value
                item.value.categoryid = item.value.categoryIds[item.value.categoryIds.length - 1]

                axios.post('/mall-manager/items/saveOrUpdate', item.value).then(rs => {
                    console.log("新增或编辑结果：", rs)
                    if (rs.data.code == 200){
                        message.success("操作成功")
                        visible.value = false
                        load()
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            const okDelete = (id:number) =>{
                axios.delete('/mall-manager/items/deleteById/' + id).then(rs=>{
                    console.log("新增或编辑结果：", rs)
                    if (rs.data.code == 200){
                        message.success("操作成功")
                        load()
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            onMounted(() => {
                axios.get('/mall-manager/category/queryAll').then(rs=>{
                    let temp = arrayToTree(rs.data.data,0);
                    console.log("分级",temp)
                    categoryList.value = temp
                })
                load()
            })

            return {
                columns,
                searchData,
                itemList,
                pagination,
                load,
                handlerChange,
                rest,
                visible,
                openModal,
                item,
                handleOk,
                okDelete,
                fileList,
                loading,
                beforeUpload,
                handleChange,
                categoryList,
                cascaderChange
            }
        }
    }
</script>

<style scoped>

</style>